import {
	defineStore
} from 'pinia'
import {
	ref,
	computed
} from 'vue'
import {
	store,
	mutations
} from '@/uni_modules/uni-id-pages/common/store.js'
const db = uniCloud.database()

const uniLocalStorage = {
	getItem(key) {
		return uni.getStorageSync(key)
	},
	setItem(key, value) {
		uni.setStorageSync(key, value)
	}
}
export const useNotificationStore = defineStore('notification', () => {
		// 声明数据
		const notifList = ref([])

		// 声明操作数据的方法
		const getNotification = async () => {
			// 支持异步
			const res = await db.collection('wallpaper-notification-center').where(
				`"user_id == '${store.userInfo._id}'"`).orderBy("create_time desc").get()
			// console.log(res.result.data);
			notifList.value = res.result.data
			// uni.setStorageSync('notification', notifList.value)
			try {
				if (notifCount.value > 0) {
					await uni.setTabBarBadge({
						index: 4,
						text: notifCount.value.toString()
					})
				} else {
					await uni.removeTabBarBadge({
						index: 4
					})
				}
			} catch (e) {
			}

		}
		const delNotification = async (_id) => {
			try{
				const res = await db.collection('wallpaper-notification-center').where(
					`"_id == '${_id}'"`).remove()
				notifList.value = notifList.value.filter(item => item._id !== _id)
				// console.log(res);
			}catch(e){
				console.log(e);
			}
		}
		const delAllNotification = async (user_id) => {
			try{
				const res = await db.collection('wallpaper-notification-center').where(
					`"user_id == '${user_id}'"`).remove()
				clearNotification()
				// console.log(res);
			}catch(e){
				console.log(e);
			}
		}
		const clearNotification = async () => {
			notifList.value = []
			try {
				await uni.removeTabBarBadge({
					index: 4
				})
			} catch (e) {
				//TODO handle the exception
			}
		}
		const notifCount = computed(() => notifList.value.length)

		return {
			notifList,
			notifCount,
			getNotification,
			clearNotification,
			delNotification,
			delAllNotification
		}
	},
	// {
	// 	persist:  {
	// 		enabled: true,
	// 		strategies: [
	// 		  {
	// 			key: 'notification', // 在存储中使用的键名
	// 			storage: uniLocalStorage, // 针对小程序使用 uni 存储
	// 			paths: ['notifList', 'notifCount'], // 只持久化 notifList 和 notifCount
	// 		  },
	// 		],
	// 	}
	// },
)